package com.wangp.mywrite.s_netty.chat_group.server.handler;

import com.wangp.mywrite.s_netty.chat_group.message.RpcRequestMessage;
import com.wangp.mywrite.s_netty.chat_group.message.RpcResponseMessage;
import com.wangp.mywrite.s_netty.chat_group.server.service.HelloService;
import com.wangp.mywrite.s_netty.chat_group.server.service.ServicesFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author tooStronger
 * @date 2023/4/24
 */
@Slf4j
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) {
        RpcResponseMessage response = new RpcResponseMessage();
        int sequenceId = msg.getSequenceId();
        response.setSequenceId(sequenceId);
        try {
            HelloService service = (HelloService) ServicesFactory.getService(Class.forName(msg.getInterfaceName()));
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParameterTypes());
            Object invoke = method.invoke(service, msg.getParameterValue());
            response.setReturnValue(invoke);
        } catch (Exception e) {
            log.error("error is  ", e);
            String message = e.getCause().getMessage();
            response.setExceptionValue(new RuntimeException("远程调用出错:"+message));
        }
        ctx.writeAndFlush(response);
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        RpcRequestMessage message = new RpcRequestMessage(1,
                "com.wangp.mywrite.s_netty.chat_group.server.service.HelloService",
                "sayHello",
                String.class,
                new Class[]{String.class},
                new Object[]{"zhangsan"});
        HelloService service = (HelloService) ServicesFactory.getService(Class.forName(message.getInterfaceName()));
        Method method = service.getClass().getMethod(message.getMethodName(), message.getParameterTypes());
        Object invoke = method.invoke(service, message.getParameterValue());
        System.out.println(invoke);
    }
}
